from django.shortcuts import render

from django.http import HttpResponse

from django.contrib.auth import authenticate, login,logout

# Create your views here.


def index(request):

    # return HttpResponse('后端页面')
    return render(request,'myadmin/index.html')


# 文件上传的函数
def uploads(myfile):
    # 导入模块
    import time,random
    from web.settings import BASE_DIR

    filename = str(time.time())+str(random.randint(10000,99999))+'.'+myfile.name.split('.').pop()
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")
    # 分块写入文件 
    for chunk in myfile.chunks():       
        destination.write(chunk)  
    destination.close()

    return "/static/pics/"+filename


# 登录
def mylogin(request):
    if request.method == 'GET':

        # 返回一个登录页面
        return render(request,'myadmin/login.html')

    elif request.method == 'POST':

        # 使用django提供的后台验证方法
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            #登录
            login(request,user)
            return HttpResponse('<script>location.href="/myadmin/"</script>')

        return HttpResponse('<script>alert("用户名或密码不存在");location.href="/myadmin/login/"</script>')

    #     # 执行登录

    #     if request.POST['username'] == 'admin' and request.POST['password'] == '123456':
    #         # 执行登陆
    #         request.session['AdminUser'] = {'username':'admin','uid':10}
    #         return HttpResponse('<script>alert("登录成功");location.href="/myadmin/"</script>')
        
    # return HttpResponse('<script>alert("用户名或密码错误");location.href="/myadmin/login/"</script>')


# 退出
def mylogout(request):
    # request.session['AdminUser'] = None
    logout(request)
    return HttpResponse('<script>alert("欢迎下次登录");location.href="/myadmin/login/"</script>')